<template>
  <div>
    <el-card shadow="never" class="result-container">
      <div class="day-scroll-container">
        <div class="day-scroll">
          <div
            v-for="(dayResult, index) in list"
            :key="index"
            class="day-card"
            :class="{ 'active-card': activeIndex === index }"
            @click="handleDayClick(dayResult, index)"
          >
            <div class="day-show">{{ dayResult.dayShow }}<span class="week">周{{ dayResult.week
              }}</span></div>
            <div class="match-stats">
              <div class="stat-item stat-highlight">选 {{ dayResult.selectCount }} 中
                {{ dayResult.shoot }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 比赛列表表格 - 紧凑模式 -->
    <el-table
      :data="currentMatchList"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
      class="compact-table"
      :header-cell-style="{
        background: '#f5f7fa',
        color: '#606266',
        padding: '1px 0',
        fontSize: '13px',
        textAlign: 'center',
        height: '40px'
      }"
      :cell-style="{
        padding: '1px 0',
        textAlign: 'center',
        lineHeight: '20px'
      }"
    >
      <el-table-column prop="number" label="编号" width="75" align="center">
        <template #default="{ row }">
          <a class="no-underline" :href="row.analysis" target="_blank">{{ row.number }}</a>
        </template>
      </el-table-column>

      <el-table-column prop="matchName" label="赛事名称" width="100" align="center">
        <template #default="{ row }">
          <a class="no-underline match-tag"
             :style="{ backgroundColor: row.color }"
             :href="row.matchUrl"
             target="_blank"
          >{{ row.matchName }}</a>
        </template>
      </el-table-column>

      <el-table-column prop="openTime" label="开赛时间" width="90" align="center" />

      <el-table-column prop="deadline" label="截止投注" width="90" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.deadline) }}
        </template>
      </el-table-column>

      <el-table-column label="主队" width="90" align="center">
        <template #default="{ row }">
          <div class="td-sort">
            <span v-if="row.selectSort && Number(row.selectSort) > 0" class="ico-sort">
              {{ row.selectSort }}
            </span>
            <a class="no-underline team-link" :href="row.homeTeamUrl"
               target="_blank">{{ row.homeTeam }}</a>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="(半场)全场" width="90" align="center">
        <template #default="{ row }">
          <a class="no-underline score"
             :href="`https://odds.500.com/fenxi/shuju-${row.matchId}.shtml`"
             target="_blank"
          >{{ row.halfFullCourt }}</a>
        </template>
      </el-table-column>

      <el-table-column label="客队" width="90" align="center">
        <template #default="{ row }">
          <a class="no-underline team-link" :href="row.visitTeamUrl"
             target="_blank">{{ row.visitingTeam }}</a>
        </template>
      </el-table-column>

      <el-table-column label="比分推荐" width="200" align="center">
        <template #default="{ row }">
          <template v-if="row.teamScore">
            <div class="score-prediction">
              <div class="prediction-row">
                <span class="prediction-label">推测值</span>
                <span>（{{ row.homePreScoreBan }}:{{ row.awayPreScoreBan }}）【{{ row.scoreSelect
                  }}】</span>
              </div>
              <div class="prediction-row">
                <span class="prediction-label">精算值</span>
                <span>（{{ row.homeAlgScoreBan }}:{{ row.awayAlgScoreBan }}）【{{ row.homeAlgScoreQuan
                  }}:{{ row.awayAlgScoreQuan }}】</span>
              </div>
              <div class="prediction-row">
                <span class="prediction-label">进球差</span>
                <span>&nbsp;&nbsp;{{ row.ballDiff }}</span>
              </div>
              <div class="prediction-row" v-if="row.ouResult">
                <span class="prediction-label">方向值</span>
                <span class="direction-value">&nbsp;&nbsp;{{ row.ouResult }}</span>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="no-data">4点开放</div>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="进球推荐" width="100" align="center">
        <template #default="{ row }">
          <div v-if="row.teamScore" class="goal-prediction">
            <div class="prediction-row">
              <span class="prediction-label">推测值</span>
              <span>{{ row.ballNum }}</span>
            </div>
            <div class="prediction-row">
              <span class="prediction-label">精算值</span>
              <span>{{ row.ballNumPredict }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="让球" width="55" align="center">
        <template #default="{ row }">
          <div class="handicap">
            <p style="position: absolute; top: 0; left: 0; margin: 0;">
              <span v-if="row.isSingle === '1'" class="ico-dg">单</span>
            </p>
            <p class="itm-rangA1" title="不让球">
              0
            </p>
            <p class="itm-rangA2" :title="getHandicapTitle(row.letBall)">
              {{ row.letBall }}
            </p>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="胜平负" width="160" align="center">
        <template #header>
          <div class="odds-header">
            <div class="odds-row">
              <span>胜</span>
              <span>平</span>
              <span>负</span>
            </div>
          </div>
        </template>
        <template #default="{ row }">
          <div class="odds-grid">
            <div class="odds-row">
              <span
                @click="selectPay(row.matchId, 1)"
                :class="['odds-item', { 'win-pay': row.winFlag === 1, 'selected': row.winSelect === 1 }]"
              >{{ row.winPay }}</span>
              <span
                @click="selectPay(row.matchId, 2)"
                :class="['odds-item', { 'win-pay': row.drawWinFlag === 1, 'selected': row.drawWinSelect === 1 }]"
              >{{ row.drawPay }}</span>
              <span
                @click="selectPay(row.matchId, 3)"
                :class="['odds-item', { 'win-pay': row.visitWinFlag === 1, 'selected': row.visitWinSelect === 1 }]"
              >{{ row.visitPay }}</span>
            </div>
            <div class="divider"></div>
            <div class="odds-row">
              <span
                @click="selectPay(row.matchId, 4)"
                :class="['odds-item', { 'win-pay': row.letWinFlag === 1, 'selected': row.letWinSelect === 1 }]"
              >{{ row.letWinPay }}</span>
              <span
                @click="selectPay(row.matchId, 5)"
                :class="['odds-item', { 'win-pay': row.letDrawWinFlag === 1, 'selected': row.letDrawWinSelect === 1 }]"
              >{{ row.letDrawPay }}</span>
              <span
                @click="selectPay(row.matchId, 6)"
                :class="['odds-item', { 'win-pay': row.letVisitWinFlag === 1, 'selected': row.letVisitWinSelect === 1 }]"
              >{{ row.letVisitPay }}</span>
            </div>
            <div class="divider"></div>
            <div class="more-play-button-container">
              <button
                class="more-play-button"
              >
                更多玩法
                <span class="arrow-icon" :class="{ 'expanded': row.expanded }">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none"
                   xmlns="http://www.w3.org/2000/svg">
                <path d="M7 10L12 15L17 10" stroke="currentColor" stroke-width="2"
                      stroke-linecap="round" stroke-linejoin="round" />
              </svg>
            </span>
              </button>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="赔率差异" width="220" align="center">
        <template #header>
          <div class="diff-header">
            <div class="diff-row">
              <span>胜赔差异</span>
              <span>平赔差异</span>
              <span>负赔差异</span>
            </div>
          </div>
        </template>
        <template #default="{ row }">
          <div class="diff-grid">
            <div class="diff-row">
              <span class="diff-item">{{ row.winRate }}</span>
              <span class="diff-item">{{ row.drawWinRate }}</span>
              <span class="diff-item">{{ row.visitWinRate }}</span>
            </div>
            <div class="divider"></div>
            <div class="diff-row">
              <span class="diff-item">{{ row.letWinRate }}</span>
              <span class="diff-item">{{ row.letDrawWinRate }}</span>
              <span class="diff-item">{{ row.letVisitWinRate }}</span>
            </div>
            <div class="divider"></div>
            <div class="diff-row">
              <span class="diff-item">{{ row.minusWinRate }}</span>
              <span class="diff-item">{{ row.minusDrawWinRate }}</span>
              <span class="diff-item">{{ row.minusVisitWinRate }}</span>
            </div>
            <template v-if="row.ouHomeRate">
              <div class="divider"></div>
              <div class="diff-row">
                <span class="diff-item">{{ row.ouHomeRate }}</span>
                <span class="diff-item">{{ row.ouDrawRate }}</span>
                <span class="diff-item">{{ row.ouVisitRate }}</span>
              </div>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { FootballMatchApi } from '@/api/lottery/sporttery/footballmatch';
  import type { FootballDayResultVO, AppFootballMatchRespVO } from './football';
  import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
  import dayjs from 'dayjs';

  defineOptions({ name: 'FootballDayResults' });

  const loading = ref(true);
  const list = ref<FootballDayResultVO[]>([]);
  const currentMatchList = ref<AppFootballMatchRespVO[]>([]);
  const activeIndex = ref<number | null>(null);

  const queryParams = reactive({
    pageNo: 0,
    pageSize: 10,
  });

  // 从sessionStorage获取保存的activeIndex
  const getSavedActiveIndex = (): number | null => {
    const savedIndex = sessionStorage.getItem('footballDayResultsActiveIndex');
    return savedIndex !== null ? parseInt(savedIndex) : null;
  };

  // 保存activeIndex到sessionStorage
  const saveActiveIndex = (index: number | null) => {
    if (index !== null) {
      sessionStorage.setItem('footballDayResultsActiveIndex', index.toString());
    } else {
      sessionStorage.removeItem('footballDayResultsActiveIndex');
    }
  };

  // 获取当天日期的索引
  const getTodayIndex = (data: FootballDayResultVO[]): number => {
    const today = dayjs().format('YYYY-MM-DD');
    return data.findIndex(item => item.dayShow === today);
  };

  const getList = async () => {
    loading.value = true;
    try {
      const data = await FootballMatchApi.getDayResultList(queryParams);
      list.value = data;

      if (data.length > 0) {
        // 尝试从sessionStorage中恢复上次选中的索引
        const savedIndex = getSavedActiveIndex();

        // 确定初始显示的索引：
        // 1. 如果有保存的索引且有效，使用保存的索引
        // 2. 否则尝试显示当天日期
        // 3. 否则显示最后一个日期
        let initialIndex = data.length - 1; // 默认最后一个

        const todayIndex = getTodayIndex(data);
        if (todayIndex !== -1) {
          initialIndex = todayIndex;
        }

        if (savedIndex !== null && savedIndex < data.length) {
          initialIndex = savedIndex;
        }

        activeIndex.value = initialIndex;
        currentMatchList.value = data[initialIndex].matchList;
      }
    } finally {
      loading.value = false;
    }
  };

  const formatDateTime = (dateTime: string | number | Date) => {
    if (!dateTime) return '-';
    return dayjs(dateTime).format('MM-DD HH:mm');
  };

  const getHandicapTitle = (letBall: string) => {
    const num = parseInt(letBall);
    return num > 0
      ? `主队受让${Math.abs(num)}球`
      : `主队让${Math.abs(num)}球`;
  };

  const selectPay = async (matchId, index) => {
    ElMessageBox.confirm('确定要选择这个选项吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const loading = ElLoading.service({ text: '操作中...' });
      try {
        const response = await FootballMatchApi.footballSelect(matchId, index);
        if (response)
          await getList();
      } catch (error) {
        ElMessage.error('选择异常');
      } finally {
        loading.close();
      }
    }).catch(() => {
      ElMessage.info('操作已取消');
    });
  };

  const handleDayClick = (dayResult: FootballDayResultVO, index: number) => {
    activeIndex.value = index;
    currentMatchList.value = dayResult.matchList;
    // 保存当前选中的索引
    saveActiveIndex(index);
  };

  onMounted(() => {
    getList();
    activeIndex.value = getTodayIndex();
  });
</script>

<style scoped>
  /* 紧凑表格样式 */
  .compact-table {
    font-size: 12px;
    margin-top: 10px;
  }

  /* 同时控制表头和内容单元格 */
  .compact-table :deep(.el-table th.el-table__cell),
  .compact-table :deep(.el-table td.el-table__cell) {
    padding-left: 1px;
    padding-right: 1px;
  }

  .compact-table :deep(.el-table__cell) {
    padding: 1px 0;
    line-height: 0;
  }

  .compact-table :deep(.el-table__header-wrapper) {
    font-size: 12px;
  }

  /* 链接样式 */
  .no-underline {
    text-decoration: none;
  }

  .match-tag {
    display: inline-block;
    min-width: 70px;
    height: 22px;
    line-height: 22px;
    text-align: center;
    color: white;
    border-radius: 3px;
    padding: 0 4px;
  }

  .team-link {
    color: #333;
    transition: color 0.2s;
  }

  .team-link:hover {
    color: #409eff;
  }

  .score {
    color: #f56c6c;
    font-weight: bold;
  }

  /* 比分推荐样式 */
  .score-prediction {
    font-size: 11px;
    line-height: 1.4;
  }

  .prediction-row {
    display: flex;
    margin-bottom: 2px;
  }

  .prediction-label {
    flex: 0 0 40px;
    background-color: #bb5753;
    color: white;
    text-align: center;
    margin-right: 4px;
    border-radius: 2px;
  }

  .direction-value {
    font-weight: bold;
    color: #f56c6c;
  }

  .no-data {
    color: #909399;
    font-style: italic;
  }

  /* 让球样式 */
  .handicap {
    line-height: 1.4;
  }

  .itm-rangA1 {
    margin: 0;
    font-size: 11px;
  }

  .itm-rangA2 {
    margin: 0;
    color: #67c23a;
    font-weight: 500;
  }

  .ico-dg {
    display: inline-block;
    background-color: #f56c6c;
    color: white;
    font-size: 11px;
    padding: 0 2px;
    border-radius: 2px;
    margin-right: 2px;
  }

  /* 赔率样式 */
  .odds-grid, .diff-grid {
    display: flex;
    flex-direction: column;
    gap: 1px;
  }

  .odds-row, .diff-row {
    display: flex;
    justify-content: space-around;
    gap: 1px;
  }

  .odds-item, .diff-item {
    flex: 1;
    text-align: center;
    padding: 0 2px;
    min-width: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .odds-item {
    cursor: pointer;
    transition: all 0.2s;
  }

  .odds-item:hover {
    background-color: #f5f7fa;
  }

  .win-pay {
    color: #f56c6c;
    font-weight: bold;
  }

  .selected {
    background-color: #ff0 !important;
  }

  .divider {
    height: 1px;
    background-color: #ebeef5;
    margin: 1px 0;
  }

  /* 确保表头内容居中 */
  .odds-header, .diff-header {
    width: 100%;
  }

  .odds-header .odds-row,
  .diff-header .diff-row {
    display: flex;
    justify-content: space-around;
    gap: 1px;
  }

  .odds-header span,
  .diff-header span {
    flex: 1;
    text-align: center;
  }

  .result-container {
    border-radius: 8px;
    display: flex;
    justify-content: center; /* 卡片内容水平居中 */
  }

  .day-scroll-container {
    width: 100%;
    overflow-x: auto;
    text-align: center; /* 内部内容居中 */
  }

  .day-scroll {
    display: inline-flex; /* 使用inline-flex使内容根据实际宽度居中 */
    gap: 12px;
    padding: 0 16px;
  }

  .day-card {
    flex: 0 0 auto;
    width: 90px;
    padding: 2px;
    background: white;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.2s;
    border: 1px solid #ebeef5;
    text-align: center; /* 卡片内部内容居中 */
  }

  .day-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .day-card.active-card {
    background-color: #f5f7fa;
    border-color: #409eff;
    box-shadow: 0 1px 6px rgba(64, 158, 255, 0.3);
  }

  .day-show {
    font-size: 13px;
    font-weight: 500;
    margin-bottom: 8px;
  }

  .week {
    font-size: 11px;
    color: #909399;
    margin-left: 4px;
  }

  .match-stats {
    display: flex;
    justify-content: space-around;
    font-size: 11px;
  }

  .stat-item {
    padding: 2px 6px;
    border-radius: 4px;
  }

  .stat-highlight {
    background-color: #f0f7ff; /* 浅蓝色背景 */
    box-shadow: 0 1px 3px rgba(64, 158, 255, 0.2); /* 蓝色阴影 */
    color: red; /* 蓝色文字 */
    font-weight: bold;
  }

  /* 滚动条样式 */
  .day-scroll-container::-webkit-scrollbar {
    height: 4px;
  }

  .day-scroll-container::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  .day-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 2px;
  }

  .day-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }

  /* 展开按钮样式 */
  .more-play-button-container {
    display: flex;
    justify-content: center;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 2px;
    margin: 0 auto;
  }

  .more-play-button {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px 12px;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #606266;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.3s;
    outline: none;
  }

  .more-play-button:hover {
    background-color: #ecf5ff;
    border-color: #c6e2ff;
    color: #409eff;
  }

  .arrow-icon {
    margin-left: 4px;
    transition: transform 0.3s;
    display: flex;
    align-items: center;
  }

  .arrow-icon.expanded {
    transform: rotate(180deg);
  }
</style>
